package com.huacai.collect.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;

import com.huacai.blog.domain.MyBlogData;
import com.huacai.common.utils.DateUtils;
import com.huacai.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huacai.collect.mapper.CollectMapper;
import com.huacai.collect.domain.Collect;
import com.huacai.collect.service.ICollectService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.util.CollectionUtils;

import static com.huacai.common.utils.SecurityUtils.getUserId;

/**
 * 博客收藏Service业务层处理
 *
 * @author lundao
 * @date 2025-09-14
 */
@Service
public class CollectServiceImpl implements ICollectService
{
    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    /**
     * 根据userId和blogId删除博客收藏
     * @param blogId
     * @return
     */
    @Override
    public int deleteCollectByUserIdAndBlogId(String blogId) {
        Integer userId = Math.toIntExact(getUserId());
        return collectMapper.deleteCollectByUserIdAndBlogId(userId, blogId);
    }
    /**
     * 根据userId和blogId删除博客收藏
     * @param blogId
     * @return
     */

    /**
     * 查询博客收藏
     *
     * @param collectId 博客收藏主键
     * @return 博客收藏
     */
    public Collect selectCollectByCollectId(String collectId){

        return null;
    }
    /**
     * 批量查询收藏数
     * @param blogIds
     * @return
     */
    /**
     * 批量查询收藏数
     *
     * @param blogIds
     * @return
     */
    /**
     * 批量查询收藏数
     *
     * @param blogIds
     * @return
     */
    /**
     * 批量查询收藏数
     * @param blogIds
     * @return
     */
    @Override
    public Map<String, Integer> batchSelectCollectCount(List<String> blogIds) {
        if (blogIds == null || blogIds.isEmpty()) {
            return Collections.emptyMap();
        }
        //每批处理500个ID
        int batchSize = 500;
        Map<String, Integer> finalResult = new HashMap<>();
        //分批处理
        for (int i = 0; i < blogIds.size(); i += batchSize) {
            int end = Math.min(i + batchSize, blogIds.size());
            List<String> batchIds = blogIds.subList(i, end);
            Map<String, Map<String, Object>> resultMap = collectMapper.batchSelectCollectCount(batchIds);
            resultMap.forEach((blogId, data) ->
                    finalResult.put(blogId, ((Number) data.get("collectCount")).intValue()));
        }
        return finalResult;
    }
    /**
     * 查询博客收藏列表
     *
     * @param collect 博客收藏
     * @return 博客收藏
     */
    @Override
    public List<Collect> selectCollectList(Collect collect)
    {
        return collectMapper.selectCollectList(collect);
    }


    @Override
    public int selectCollectCount(String blogId) {
        return collectMapper.selectCollectCount(blogId);
    }
    /**
     * 新增博客收藏
     *
     * @param collect 博客收藏
     * @return 结果
     */
    @Override
    public int insertCollect(Collect collect)
    {
        collect.setCreateTime(DateUtils.getNowDate());
        collect.setCollectId(IdUtils.randomUUID());
        collect.setUserId(Math.toIntExact(getUserId()));
        return collectMapper.insertCollect(collect);
    }

    /**
     * 批量新增博客收藏
     *
     * @param collects 博客收藏List
     * @return 结果
     */
    @Override
    public int batchInsertCollect(List<Collect> collects)
    {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        int count = 0;
        if (!CollectionUtils.isEmpty(collects)) {
            try {
                for (int i = 0; i < collects.size(); i++) {
                    int row = collectMapper.insertCollect(collects.get(i));
                    // 防止内存溢出，每100次提交一次,并清除缓存
                    boolean bool = (i >0 && i%100 == 0) || i == collects.size() - 1;
                    if (bool){
                        sqlSession.commit();
                        sqlSession.clearCache();
                    }
                    count = i + 1;
                }
            }catch (Exception e){
                e.printStackTrace();
                // 没有提交的数据可以回滚
                sqlSession.rollback();
            }finally {
                sqlSession.close();
                return count;
            }
        }
        return count;
    }

    /**
     * 修改博客收藏
     *
     * @param collect 博客收藏
     * @return 结果
     */
    @Override
    public int updateCollect(Collect collect)
    {
        return collectMapper.updateCollect(collect);
    }

    /**
     * 批量删除博客收藏
     *
     * @param collectIds 需要删除的博客收藏主键
     * @return 结果
     */
    @Override
    public int deleteCollectByCollectIds(String[] collectIds)
    {
        return collectMapper.deleteCollectByCollectIds(collectIds);
    }

    /**
     * 删除博客收藏信息
     *
     * @param collectId 博客收藏主键
     * @return 结果
     */
    @Override
    public int deleteCollectByCollectId(String collectId)
    {
        return 0;
    }

    /**
     * 判断当前用户有没有对某个博客点过赞
     * @param blogId
     * @return
     */

    public int selectCollectByUserIdAndBlogId(String blogId) {
        Integer userId = Math.toIntExact(getUserId());
        return collectMapper.selectCollectByUserIdAndBlogId( userId,blogId);
    }

    /**
     * 查询当前登录用户的博客数据
     * @return
     */
    @Override
    public MyBlogData selectBlogDataByUserId() {
        Integer userId = Math.toIntExact(getUserId());
        return collectMapper.selectBlogDataByUserId(userId);
    }
}
